<?php
use App\Models\MUser;
use Illuminate\Support\Facades\DB;

/**
 * 接口返回提示信息
 * @param int $key
 * @return string
 */
function getMessage($key =0){
    switch ($key){
        case 1:
            return '获取失败';
        case 2 :
            return  '登录成功';
        case 3:
            return  '登录失败';
        case 4:
            return  '操作成功';
        case 5:
            return  '操作失败';
        case 6:
            return  '提现成功';
        case 7:
            return  '余额不足';
        default:
            return '获取成功';
    }
}
/**
 * 获取随机字符串
 * @param int $randLength 长度
 * @param int $addtime 是否加入当前时间戳
 * @param int $includenumber 是否包含数字
 * @return string
 */
function get_rand_str($randLength = 6, $addtime = 0, $includenumber = 1)
{
    if ($includenumber) {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNPQEST123456789';
    } else {
        $chars = 'abcdefghijklmnopqrstuvwxyz';
    }
    $len = strlen($chars);
    $randStr = '';
    for ($i = 0; $i < $randLength; $i++) {
        $randStr .= $chars[rand(0, $len - 1)];
    }
    $tokenvalue = $randStr;
    if ($addtime) {
        $tokenvalue = $randStr . time();
    }
    return $tokenvalue;
}
/**
 * 获取随机字符串
 * @param int $randLength 长度
 * @param int $addtime 是否加入当前时间戳
 * @param int $includenumber 是否包含数字
 * @return string
 */
function get_rand_account($randLength = 6)
{
    $chars = 'abcdefghijklmnopqrstuvwxyz1234567890';
    $len = strlen($chars);
    $randStr = '';
    for ($i = 0; $i < $randLength; $i++) {
        $randStr .= $chars[rand(0, $len - 1)];
    }
    $tokenvalue = $randStr;
    $account = DB::table('users')->where('account',$randStr)->first();
    if($account){
        get_rand_account();
    }
    return $tokenvalue;
}

//格式化数字
/**
 * @param $pid 上级的id
 * @param $user_id
 */
function relationUser($pid, $user_id)
{
    $list =    DB::table('user_relation')->where('user_id',$pid)->get()->toArray();
    $user = \App\Admin\Models\Users::find($user_id);
    $newList = [];
    $newList[0]['user_id'] = $user_id;
    $newList[0]['pid'] = $pid;
    $newList[0]['p_account'] = $user->account;
    $newList[0]['lay'] = 1;
    $newList[0]['created_at'] = time();
    if ($list)
    {
        foreach ($list as $k => $v)
        {
            $newList[$k + 1]['user_id'] = $user_id;
            $newList[$k + 1]['pid'] = $v->pid;
            $newList[$k + 1]['p_account'] = $user->account;
            $newList[$k + 1]['lay'] = $v->lay + 1;
            $newList[$k + 1]['created_at'] = time();
        }
    }

    return DB::table('user_relation')->insert($newList);
}
/**
 * @param $num
 * @param $k 保留几位
 * @return float|int eg $k=2  7.0 返回7.0 如果为7.0001 则返回7.00
 */
function number_make($num,$k){
    //舍去法
    //$num  要处理的数字  $k 保留小数点的位数
    $number = floor(bcmul($num,pow(10,$k)))*(1/pow(10,$k));
    return $number;
}
//获取对应等级返佣代数及比例
function get_rate($con,$lv,$dai){
    $rate = 0;
    if($lv == 1){
        if($dai == 1){
            $rate = $con['lv1_rate1'];
        }
    }
    if($lv == 2){
        if($dai <= 2){
            $rate = $con['lv2_rate'.$dai];
        }
    }
    if($lv == 3){
        if($dai <=3 ){
            $rate = $con['lv3_rate'.$dai];
        }else{
            for($i=4;$i<=7;$i++){
                if($dai >= $con['lv3_dai'.$i.'_min']){
                    $rate = $con['lv3_rate'.$i];
                }
            }
        }

    }
    return $rate;

}
/**
 * 系统返佣
 * @param $pid 上级的id
 * @param $user_id
 */
function systemCommissions($user_id,$order_id)
{
    $order_info  = DB::table('shop_orders')->where(['order_sn'=>$order_id,'status'=>2])->first();
    if($order_info )
    {
        $goods_info = DB::table('shop_goods')->where('id',$order_info->goods_id)->where('is_earnings',1)->first();

        if($goods_info)
        {
            $list = DB::table('user_relation')
                ->leftJoin('users as u', 'u.id', '=', 'user_relation.pid')
                ->where('user_relation.user_id',$user_id)
                ->where('user_relation.lay','<=',2)
                ->select('user_relation.*','u.level')
                ->orderBy('lay','desc')->get();

            if(count($list)>0)
            {
                foreach ($list as $key =>$val)
                {

                    if($val->level>=1)
                    {
                        continue;
                    }
                    $insart_arr = array();
                    if($val->lay==1)
                    {
                        $insart_arr['money'] =$goods_info->zearnings;
                    }
                    else if($val->lay==2)
                    {
                        //下级级别高于上级，不能拿间接推荐奖励
                        $insart_arr['money'] =$goods_info->jearnings;
                    }
                    else
                    {
                        break;
                    }

                    $insart_arr['user_id'] = $val->pid;
                    $insart_arr['goods_id'] = $goods_info->id;
                    $insart_arr['buy_user_id'] = $user_id;
                    $insart_arr['created_at'] = date('Y-m-d H:i:s',time());
                    //收益不能为0

                    if($insart_arr['money'])
                    {

                        $res = DB::table('users_commission')->insert($insart_arr);
                        if($res)
                        {
                            DB::table('users')->where('id',$val->pid)->increment('cash_money', $insart_arr['money']);
                           $cash_user = DB::table('users')->where('id',$val->pid)->first();
//
//                            //返佣提醒
                            cash_message($cash_user->watchid,$insart_arr['money'],$cash_user->cash_money);
                        }
                    }
                    else
                    {
                        continue;
                    }

                }
            }
        }
    }

}

/**
 * 写日志
 *
 */
function writeLogs($data, $msg, $type){
//    $base_path = rtrim($_SERVER['DOCUMENT_ROOT'],'/')."/logs/".date('Y-m-d', time()).'/';
    $base_path = rtrim(public_path(),'/')."/logs/".date('Y-m-d', time()).'/';
    if ( !file_exists($base_path) ) {
        mkdir($base_path,0777,true);
        echo $base_path;
    }
    $myfile = $base_path  . $type ."_log.log";
    $times = date('Y-m-d H:i:s', time());
    $string = $times.'======>'. json_encode($data). '，msg:'. $msg ."\n\r";
    file_put_contents($myfile, $string , FILE_APPEND);
}

function cash_message($openid,$cash_money,$total_moeny=0.00){
    $appid = "wxc31bdf2ce95010be";
    $secret = "94e8c1e47f2371633346efe807c7da2b";
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
    $token =getJson($url);
    $token = json_decode($token, true);
    $uri ='https://api.weixin.qq.com/cgi-bin/message/template/send';
    $access_token = $token["access_token"];
    $uri = $uri.'?access_token='.$access_token;
    $user  = DB::table('users')->where(['watchid'=>$openid])->first();
    if(!$user){
        return false;
    }

    $data=  array('touser'=>$openid,   //发给谁
        'template_id'=>'vqknf1d95dmu3dPkY7a1bZR1MIzLDKAKlJDqYRUwqsg',   //模板id
//        'url'=>'#',     //这个是你发送了模板消息之后，当用户点击时跳转的连接
        'topcolor'=>"#FF0000",   //颜色
//        'miniprogram' => '',
        'data'=>array(

            'first'=>array(
                'value'=>$user->nickname,
                'color'=>'#173177'
            ),
            'keyword1'=>array(
                'value'=>number_make($cash_money,2),
                'color'=>'#173177'
            ),
            'keyword2'=>array(
                'value'=>'佣金到账',
                'color'=>'#173177'
            ),
            'keyword3'=>array(
                'value'=>'成功',
                'color'=>'#173177'
            ),
            'keyword4'=>array(
                'value'=>number_make($total_moeny,2),
                'color'=>'#173177'
            ),
            'remark'=>array(
                'value'=>'佣金已到账,请注意查看',
                'color'=>'#173177'
            )
        )
    );
    $res_data = getJson($uri,$data);
    $res_data = json_decode($res_data, true);
    if ($res_data['errcode'] != 0) {
        return false;
    }
    return true;
}

function getJson($url = '', $param = [] ,$contentType = 'json'){
    $ch = curl_init();
    // 请求地址
    curl_setopt($ch, CURLOPT_URL, $url);
    // 请求参数类型
    $param = $contentType == 'json' ? urldecode(json_encode($param)) : http_build_query($param);
    // 关闭https验证
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    // post提交
    if($param){
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
    }
    // 返回的数据是否自动显示
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    // 执行并接收响应结果
    $output = curl_exec($ch);
    // 关闭curl
    curl_close($ch);
    return $output !== false ? $output : false;

}

/**
 * 获取推广的二维码
 *
 */
function get_qrcodes($link, $image_name, $background_img){
    //生成二维码图片
    $object   = new \QRcode();
    $errorCorrectionLevel = 'L';    //容错级别
    $matrixPointSize = 20;
    $root_qrcode= "Public/image/qrcode/";
    if (!is_dir($root_qrcode)) {
        mkdir($root_qrcode,0777,true);
    }
    $fileName = "Public/image/qrcode/".$image_name.'.png';
    //生成图片大小（这个值可以通过参数传进来判断）
    $object->png($link,$fileName,$errorCorrectionLevel, $matrixPointSize, 2);
    if ( !file_exists($background_img) || !file_exists($fileName) ) {
        return false;
    }
    $qrcode = get_background_qrcode($background_img, $fileName, $image_name);
    return $qrcode;
}

/**
 * 对二维码进行拼接
 * @param string $img1  背景图
 * @param string $img2  二维码
 *
 * @return string
 */
function get_background_qrcode($img1, $img2, $qrcode_name){
    if (!file_exists($img1)) {
        return false;
    }
    $file_path= "Public/image/extension/";
    if (!is_dir($file_path)) {
        mkdir($file_path,0777,true);
    }
    $image_name = md5('all'.$qrcode_name);
    $fileName = $file_path.$image_name.'.png';
    if ( !file_exists($fileName) ) {
        $img2 = resize($img2, 270, 270);

        //创建图片的实例
        $dst = imagecreatefromstring(file_get_contents($img1));
        $src = imagecreatefromstring(file_get_contents($img2));

        list($dst_w, $dst_h) = getimagesize($img1);

        //获取水印图片的宽高
        list($src_w, $src_h) = getimagesize($img2);
        $dis_h =$dst_h-$src_h;
        $x = ($dst_w-$src_w)/2;
        imagecopymerge($dst, $src, $x, $dis_h-360, 0, 0, $src_w, $src_h, 100);//将二维码放到底图左下角 左边下边各距10像素

        //输出图片
        list($dst_w, $dst_h, $dst_type) = getimagesize($img1);
        imagepng($dst,$fileName);//保存图片
        imagedestroy($dst);
        imagedestroy($src);
    }

    $qrc  = "http://". $_SERVER["HTTP_HOST"] .'/' . $fileName;
    return $qrc;
}

// 定义方法，可用以处理正方形图片或长方形图片尺寸，按宽高比例自适应
function resize($imgsrc, $width, $height = 0) {  //参数定义为：源图片，目标宽度，目标高度
    $data = file_get_contents($imgsrc);
    $img_s = imagecreatefromstring($data);  // 获得源图片资源
    $width_s = imagesx($img_s);  // 获得源图片宽度
    $height_s = imagesy($img_s);  // 获得源图片高度

    $width_t = $width;  // 获得目标图片宽度
    $height_t = ($height == 0) ? $width : $height;  // 获得目标图片高度

    $image_t = imagecreatetruecolor($width_t, $height_t); //创建一个彩色的底图
    $white = imagecolorallocate($image_t, 255, 255, 255);
    imagefill($image_t, 0, 0, $white); // 初始化背景为白色

    if (($width_s / $height_s) < ($width_t / $height_t)) {
        $_final['width'] = $width_s * $height_t / $height_s;
        $_final['height'] = $height_t;
        $dst['x'] = ($width_t - $_final['width']) / 2;
        $dst['y'] = 0;
    } else {
        $_final['width'] = $width_t;
        $_final['height'] = $width_t * $height_s / $width_s;
        $dst['x'] = 0;
        $dst['y'] = ($height_t - $_final['height']) / 2;
    }

    ImageCopyResized($image_t, $img_s, $dst['x'], $dst['y'], 0, 0, $_final['width'], $_final['height'], $width_s, $height_s);
    $rel = imagepng($image_t, $imgsrc);
    imagedestroy($img_s);
    imagedestroy($image_t);
    return $rel ? $imgsrc : false;
}
?>